package br.unisinos.projetotcc.jarfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

import org.primefaces.model.UploadedFile;

/**
 * Problemas:
 * E se o aluno adicionar classes de diferentes pacotes?
 * E se o aluno adicionar .zip
 * 
 * @author MARVAN
 *
 */

public class GenerateJar {

	public static int buffer = 10240;

	protected void createJarArchive(File jarFile, File[] listFiles) {
		try {
			byte b[] = new byte[buffer];
			FileOutputStream fout = new FileOutputStream(jarFile);
			JarOutputStream out = new JarOutputStream(fout, new Manifest());
			for (int i = 0; i < listFiles.length; i++) {
				JarEntry addFiles = new JarEntry(listFiles[i].getName());
				addFiles.setTime(listFiles[i].lastModified());
				out.putNextEntry(addFiles);

				FileInputStream fin = new FileInputStream(listFiles[i]);
				while (true) {
					int len = fin.read(b, 0, b.length);
					if (len <= 0)
						break;
					out.write(b, 0, len);
				}
				fin.close();
			}
			out.close();
			fout.close();
			System.out.println("Jar File is created successfully.");
		} catch (Exception ex) {
		}
	}
	
	public void createJarArchive(File jarFile, List<UploadedFile> listFiles) {
		try {
			byte b[] = new byte[buffer];
			FileOutputStream fout = new FileOutputStream(jarFile);
			JarOutputStream out = new JarOutputStream(fout, new Manifest());
			
			for (UploadedFile file : listFiles) {
				JarEntry addFiles = new JarEntry(file.getFileName());
				out.putNextEntry(addFiles);
				
//				FileInputStream fin = new FileInputStream(file);
				
				InputStream in = file.getInputstream();
				
				while (true) {
					int len = in.read(b, 0, b.length);
					if (len <= 0)
						break;
					out.write(b, 0, len);
				}
				in.close();
			}
			out.close();
			fout.close();
			System.out.println("Jar File is created successfully.");
		} catch (Exception ex) {
		}
	}
	
	
	
	public static void main(String[] args) {
		GenerateJar jar = new GenerateJar();
		File folder = new File("C:\\Users\\MARVAN\\Desktop\\teste");
		File[] files = folder.listFiles();
		File file = new File("teste4.jar");
		jar.createJarArchive(file, files);
	}
}
